# bib_file_parser

import re

def bib_file_extract(bib_file_path):
    """
    从指定的 bib 文件中提取 bib entries。
    
    Args:
        bib_file_path (str): bib 文件路径。
    
    Returns:
        List[str]: 包含提取的 bib entries 的列表。
    
    """
    
    with open(bib_file_path, 'r', encoding='utf-8') as f:
        bib_content = f.read()
        bib_content = bib_content.split("\n@")
        bib_content = [i for i in bib_content if i != ""]
        bib_content = ["@" + i for i in bib_content]
        bib_content = [i.replace("@@","@") for i in bib_content]
        # bib_content = bib_content.replace("@@","@")
    return bib_content



def bib_item_list_extract(bib_item,key_word):
    """
    从BIB条目中提取给定关键字所在的行
    
    Args:
        bib_item (str): BIB条目字符串
        key_word (str): 需要提取的关键词
    
    Returns:
        str: 包含关键字的行字符串
    """
    bib_item_list = bib_item.split("\n")
    key_word_line = [i for i in bib_item_list if i.lower().strip().startswith(key_word)]
    if len(key_word_line)!=0:
        key_word_line = key_word_line[0]
    return key_word_line


def bib_item_content(bib_item,key_word):
    """
    从Bibitem中提取与关键字相关的内容
    
    Args:
        bib_item (str): Bibitem字符串
        key_word (str): 关键字
    
    Returns:
        str: 与关键字相关的内容，如果未找到则返回空字符串
    """
    
    key_word_line = bib_item_list_extract(bib_item,key_word)
    if len(key_word_line)!=0:
        key_item = bib_line_content_extract(key_word_line)
    else:
        key_item = ""
    return key_item

def bib_line_content_extract(bib_line):
    """
    从BibTex格式的字符串中提取BibLine的内容
    
    Args:
        bib_line (str): BibTex格式的字符串，格式为"{key} = {content}"
    
    Returns:
        str: BibLine的内容，即"{content}"部分
    
    """
    bib_line_content_pre = bib_line.split("=")[1:]
    if len(bib_line_content_pre)>1:
        bib_line_content_pre = "=".join(bib_line.split("=")[1:])
    else:
        bib_line_content_pre = bib_line_content_pre[0]
    # bib_line_content_pre = bib_line.split("=")[1].strip("{").strip("}")
    if "\{" in bib_line_content_pre:
        pattern = r'\{(.*?)\}'
        bib_line_content = re.findall(pattern, bib_line_content_pre)[0]
    else:
        bib_line_content = bib_line_content_pre
    return bib_line_content